<?php
namespace Auth\Controller;
 
use Zend\Mvc\Controller\AbstractActionController;
use Zend\Authentication\AuthenticationService;
use Zend\View\Model\ViewModel;
use Zend\Session\Container;
use Auth\Model\User;
use Auth\Form\RegisterForm;
 
class AuthController extends AbstractActionController
{
    protected $authService;
	protected $authTable;
	protected $userTable;
     
    //we will inject authService via factory
    public function __construct(AuthenticationService $authService)
    {
        $this->authService = $authService;
    }
     
    public function indexAction()
    {
		$this->layout('layout/login');
        if ($this->authService->getStorage()->getSessionManager()
                 ->getSaveHandler()
                 ->read($this->authService->getStorage()->getSessionId())) {
            //redirect to success controller...
			
					$sessionModule = new Container('module');
					$sessionController = new Container('controller');
					$sessionAction = new Container('action');
				
					return $this->redirect()->toRoute($sessionModule->lastModule,array('action'=>$sessionAction->lastAction));
        }
         
		 else{
			$form = $this->getServiceLocator()
						 ->get('FormElementManager')
						 ->get('Auth\Form\LoginForm');   
			$viewModel = new ViewModel();
			 
			//initialize error...
			$viewModel->setVariable('error', '');
			//authentication block...
			$this->authenticate($form, $viewModel);
			 
			$viewModel->setVariable('form', $form);
			return $viewModel;
		 }
    }
     
    /** this function called by indexAction to reduce complexity of function */
    protected function authenticate($form, $viewModel)
    {
		
        $request = $this->getRequest();
        if ($request->isPost()) {
            $form->setData($request->getPost());
            if ($form->isValid()) {
                $dataform = $form->getData();
                 
                $this->authService->getAdapter()
                                       ->setIdentity($dataform['username'])
                                       ->setCredential($dataform['password']);
                $result = $this->authService->authenticate();
                if ($result->isValid()) {
                    //authentication success
                    $resultRow = $this->authService->getAdapter()->getResultRowObject();
                    
                    $this->authService->getStorage()->write(
                         array('id'          => $resultRow->id,
                                'username'   => $dataform['username'],
                                'ip_address' => $this->getRequest()->getServer('REMOTE_ADDR'),
                                'user_agent'    => $request->getServer('HTTP_USER_AGENT'))
                    );
                     $sessionUser = new Container('user');
					 $sessionUser->tendangnhap = $dataform['username'];
					 $sessionUser->quyen = $resultRow->quyen;
					 $sessionUser->userid = $resultRow->id;
                    
					$sessionModule = new Container('module');
					$sessionController = new Container('controller');
					$sessionAction = new Container('action');
				
					return $this->redirect()->toRoute($sessionModule->lastModule,array('action'=>$sessionAction->lastAction));
					   
                } else {
                    $viewModel->setVariable('error', 'Sai tên đăng nhập hoặc mật khẩu');
                }
            }
        }
    }
     public function registerAction()
    {
        $this->layout('layout/login');
		$dbAdapter = $this->getServiceLocator()->get('Zend\Db\Adapter\Adapter');
        $form = new RegisterForm($dbAdapter);
        $form->get('submit')->setAttribute('value', 'Đăng kí');
		$viewModel = new ViewModel();
        $request = $this->getRequest();
        if ($request->isPost()) {
            $user = new User();
            $form->setInputFilter($user->getInputFilter());
            $form->setData($request->getPost());
      //      var_dump($form);
            if ($form->isValid()) {
                $user->exchangeArray($form->getData());
				if($this->getUserTable()->check_exists($_POST['username'],0)){
					$viewModel->setVariable('error', 'Tên đăng nhập đã tồn tại');
					$viewModel->setVariable('form', $form);
					return $viewModel;
				}
				else if($this->getUserTable()->check_email($_POST['email'],0)){
					$viewModel->setVariable('error', 'Email đã được sử dụng');
					$viewModel->setVariable('form', $form);
					return $viewModel;
				}
				else if($this->getUserTable()->check_cmt($_POST['cmt'],0)){
					$viewModel->setVariable('error', 'Số CMT đã được sử dụng');
					$viewModel->setVariable('form', $form);
					return $viewModel;
				}
				else{
					$this->getUserTable()->saveUser($user);
	
					// Redirect to list of users
					return $this->redirect()->toRoute('home');
				}
            }
        }

        return array('form' => $form);
    }
	public function infoAction() {
		$id = (int) $this->params('id');
		$sessionUser = new Container('user');
		if(!$sessionUser->userid){
			return $this->redirect()->toRoute('home');
		}
		else if($sessionUser->userid && $sessionUser->userid != $id){
			return $this->redirect()->toRoute('home');
		}
		
        
        else if (!$id) {
            return $this->redirect()->toRoute('home');
        }
		$viewModel = new ViewModel();
        $user = $this->getUserTable()->getUser($id);
		if (!$user) {
            return $this->redirect()->toRoute('home');
        }

		$dbAdapter = $this->getServiceLocator()->get('Zend\Db\Adapter\Adapter');
        $form = new RegisterForm($dbAdapter);
        $form->bind($user);
        $form->get('submit')->setAttribute('value', 'Cập nhật');
		$form->get('password')->setAttribute('type', 'hidden');
		$form->get('password')->setLabel('');
		

        $request = $this->getRequest();
        if ($request->isPost()) {
            $form->setData($request->getPost());
            if ($form->isValid()) {
				if($this->getUserTable()->check_exists($_POST['username'],$id)){
					$viewModel->setVariable('error', 'Tên đăng nhập đã tồn tại');
					$viewModel->setVariable('id', $id);
					$viewModel->setVariable('form', $form);
					return $viewModel;
				}
				else if($this->getUserTable()->check_email($_POST['email'],$id)){
					$viewModel->setVariable('error', 'Email đã được sử dụng');
					$viewModel->setVariable('form', $form);
					return $viewModel;
				}
				else if($this->getUserTable()->check_cmt($_POST['cmt'],0)){
					$viewModel->setVariable('error', 'Số CMT đã được sử dụng');
					$viewModel->setVariable('form', $form);
					return $viewModel;
				}
				else{
                	$this->getUserTable()->saveUser($user);

					// Redirect to list of users
					return $this->redirect()->toRoute('auth', array('action' => 'info', 'id'=>$id));
				}
            }
        }

        return array(
            'id' => $id,
            'form' => $form,
        );
    }
	
    public function logoutAction()
    {
        $this->authService->getStorage()->clear();
		$sessionUser = new Container('user');
		$sessionUser->offsetUnset('tendangnhap');
		$sessionUser->offsetUnset('quyen');
        return $this->redirect()->toRoute('home');
    }
	public function getUserTable() {
        if (!$this->userTable) {
            $sm = $this->getServiceLocator();
            $this->userTable = $sm->get('Auth\Model\UserTable');
        }
        return $this->userTable;
    }
}